#!/bin/bash
<<Usage
	# 项目本身
	wget https://raw.githubusercontent.com/hilojack/php-lib/master/git/pre-commit  -O .git/hooks/pre-commit
	chmod u+x .git/hooks/pre-commit

	# 全局
 	mkdir -p ~/.git_template/hooks
 	git config --global init.templatedir '~/.git_template'
	wget https://raw.githubusercontent.com/hilojack/php-lib/master/git/pre-commit  -O ~/.git_template/hooks/pre-commit
	chmod u+x ~/.git_template/hooks/pre-commit
Usage

function push_error(){
	ERRORS="$ERRORS\n$1"
}
ROOT_DIR="$(pwd)/";
echo $ROOT_DIR;
LIST=$(git diff-index --cached --name-only --diff-filter=ACMR HEAD)
ERRORS=""
for file in $LIST
do
    if echo "$file" | grep ".php$" > /dev/null ; then
		# Check for php grammar error
        ERROR=$(php -l "$ROOT_DIR$file" 2>&1 | grep "Parse error")
        if [[ -n "$ERROR" ]]; then
			push_error "$ERROR";
            echo "Syntax errors found in file: $file "
        fi

        # Check for xdebug statments
        ERROR=$(grep -nH xdebug_ "$ROOT_DIR$file" | sed -e 's/^/Found XDebug Statment : /')
        if [[ -n "$ERROR" ]]; then
			push_error "$ERROR";
        fi

		# Check for debuging exists
        ERROR=$(grep -HF debuging "$ROOT_DIR$file")
        if [ "$ERROR" != "" ]; then
			push_error "$ERROR";
        fi
    fi
done
if [ "$ERRORS" != "" ]; then
    echo
    echo "Found PHP parse errors: "
    echo -e $ERRORS
    echo
    echo "PHP parse errors found. Fix errors and commit again."
    exit 1
else
    echo "No PHP parse errors found. Committed successfully."
fi
